package app

import (
	"context"
	"encoding/json"
	"goldtree/internal/service"

	"github.com/gogf/gf/v2/frame/g"
)

// StockAPI 股票API包装器
type StockAPI struct {
	ctx context.Context
}

// NewStockAPI 创建股票API实例
func NewStockAPI(ctx context.Context) *StockAPI {
	return &StockAPI{ctx: ctx}
}

// GetStocks 获取股票列表
func (api *StockAPI) GetStocks(params map[string]interface{}) (map[string]interface{}, error) {
	// 转换参数
	req := &service.GetStockListReq{}

	if page, ok := params["page"]; ok {
		if p, ok := page.(float64); ok {
			req.Page = int(p)
		}
	}
	if limit, ok := params["limit"]; ok {
		if l, ok := limit.(float64); ok {
			req.Limit = int(l)
		}
	}
	if keyword, ok := params["keyword"]; ok {
		if k, ok := keyword.(string); ok {
			req.Keyword = k
		}
	}
	if market, ok := params["market"]; ok {
		if m, ok := market.(string); ok {
			req.Market = m
		}
	}
	if industry, ok := params["industry"]; ok {
		if i, ok := industry.(string); ok {
			req.Industry = i
		}
	}
	if isActive, ok := params["is_active"]; ok {
		if a, ok := isActive.(bool); ok {
			active := a
			req.IsActive = &active
		}
	}

	// 调用服务
	result, err := service.Stock.GetList(api.ctx, req)
	if err != nil {
		g.Log().Error(api.ctx, "获取股票列表失败:", err)
		return map[string]interface{}{
			"code":    1,
			"message": err.Error(),
			"data":    nil,
		}, nil
	}

	return map[string]interface{}{
		"code":    0,
		"message": "success",
		"data":    result,
	}, nil
}

// CreateStock 创建股票
func (api *StockAPI) CreateStock(stockData map[string]interface{}) (map[string]interface{}, error) {
	// 转换为请求结构
	jsonBytes, _ := json.Marshal(stockData)
	req := &service.CreateStockReq{}
	if err := json.Unmarshal(jsonBytes, req); err != nil {
		return map[string]interface{}{
			"code":    1,
			"message": "参数格式错误",
			"data":    nil,
		}, nil
	}

	result, err := service.Stock.Create(api.ctx, req)
	if err != nil {
		g.Log().Error(api.ctx, "创建股票失败:", err)
		return map[string]interface{}{
			"code":    1,
			"message": err.Error(),
			"data":    nil,
		}, nil
	}

	return map[string]interface{}{
		"code":    0,
		"message": "success",
		"data":    result,
	}, nil
}

// UpdateStock 更新股票
func (api *StockAPI) UpdateStock(id int, stockData map[string]interface{}) (map[string]interface{}, error) {
	jsonBytes, _ := json.Marshal(stockData)
	req := &service.UpdateStockReq{}
	if err := json.Unmarshal(jsonBytes, req); err != nil {
		return map[string]interface{}{
			"code":    1,
			"message": "参数格式错误",
			"data":    nil,
		}, nil
	}

	err := service.Stock.Update(api.ctx, req)
	if err != nil {
		g.Log().Error(api.ctx, "更新股票失败:", err)
		return map[string]interface{}{
			"code":    1,
			"message": err.Error(),
			"data":    nil,
		}, nil
	}

	return map[string]interface{}{
		"code":    0,
		"message": "更新成功",
		"data":    nil,
	}, nil
}

// DeleteStock 删除股票
func (api *StockAPI) DeleteStock(id int) (map[string]interface{}, error) {
	err := service.Stock.Delete(api.ctx, id)
	if err != nil {
		g.Log().Error(api.ctx, "删除股票失败:", err)
		return map[string]interface{}{
			"code":    1,
			"message": err.Error(),
			"data":    nil,
		}, nil
	}

	return map[string]interface{}{
		"code":    0,
		"message": "删除成功",
		"data":    nil,
	}, nil
}

// ImportStocks 导入股票数据
func (api *StockAPI) ImportStocks(importData map[string]interface{}) (map[string]interface{}, error) {
	jsonBytes, _ := json.Marshal(importData)
	req := &service.StockImportReq{}
	if err := json.Unmarshal(jsonBytes, req); err != nil {
		return map[string]interface{}{
			"code":    1,
			"message": "参数格式错误",
			"data":    nil,
		}, nil
	}

	result, err := service.Stock.ImportStocks(api.ctx, req)
	if err != nil {
		g.Log().Error(api.ctx, "导入股票失败:", err)
		return map[string]interface{}{
			"code":    1,
			"message": err.Error(),
			"data":    nil,
		}, nil
	}

	return map[string]interface{}{
		"code":    0,
		"message": "success",
		"data":    result,
	}, nil
}

// GetIndustries 获取行业列表
func (api *StockAPI) GetIndustries() (map[string]interface{}, error) {
	result, err := service.Stock.GetIndustryList(api.ctx)
	if err != nil {
		g.Log().Error(api.ctx, "获取行业列表失败:", err)
		return map[string]interface{}{
			"code":    1,
			"message": err.Error(),
			"data":    nil,
		}, nil
	}

	return map[string]interface{}{
		"code":    0,
		"message": "success",
		"data":    result,
	}, nil
}

// UserAPI 用户API包装器
type UserAPI struct {
	ctx context.Context
}

// NewUserAPI 创建用户API实例
func NewUserAPI(ctx context.Context) *UserAPI {
	return &UserAPI{ctx: ctx}
}

// Login 用户登录
func (api *UserAPI) Login(username, password string) (map[string]interface{}, error) {
	req := &service.LoginReq{
		Username: username,
		Password: password,
	}

	result, err := service.User.Login(api.ctx, req)
	if err != nil {
		g.Log().Error(api.ctx, "登录失败:", err)
		return map[string]interface{}{
			"code":    1,
			"message": err.Error(),
			"data":    nil,
		}, nil
	}

	return map[string]interface{}{
		"code":    0,
		"message": "success",
		"data":    result,
	}, nil
}

// GetProfile 获取用户信息
func (api *UserAPI) GetProfile(token string) (map[string]interface{}, error) {
	// 这里需要根据token获取用户信息
	// 暂时返回模拟数据
	result := map[string]interface{}{
		"username": "admin",
		"nickname": "系统管理员",
		"email":    "admin@goldtree.com",
		"role":     "admin",
	}

	return map[string]interface{}{
		"code":    0,
		"message": "success",
		"data":    result,
	}, nil
}

// ========== App API集成方法 ==========

// 在 App 结构中添加API实例
func (a *App) GetStockAPI() *StockAPI {
	return NewStockAPI(a.ctx)
}

func (a *App) GetUserAPI() *UserAPI {
	return NewUserAPI(a.ctx)
}

// 便捷方法：直接调用股票API
func (a *App) StockGetList(params map[string]interface{}) (map[string]interface{}, error) {
	return a.GetStockAPI().GetStocks(params)
}

func (a *App) StockCreate(stockData map[string]interface{}) (map[string]interface{}, error) {
	return a.GetStockAPI().CreateStock(stockData)
}

func (a *App) StockUpdate(id float64, stockData map[string]interface{}) (map[string]interface{}, error) {
	return a.GetStockAPI().UpdateStock(int(id), stockData)
}

func (a *App) StockDelete(id float64) (map[string]interface{}, error) {
	return a.GetStockAPI().DeleteStock(int(id))
}

func (a *App) StockImport(importData map[string]interface{}) (map[string]interface{}, error) {
	return a.GetStockAPI().ImportStocks(importData)
}

func (a *App) StockGetIndustries() (map[string]interface{}, error) {
	return a.GetStockAPI().GetIndustries()
}

// 便捷方法：直接调用用户API
func (a *App) UserLogin(username, password string) (map[string]interface{}, error) {
	return a.GetUserAPI().Login(username, password)
}

func (a *App) UserGetProfile(token string) (map[string]interface{}, error) {
	return a.GetUserAPI().GetProfile(token)
}
